const weiUser = require('wei-user');
const { decryptAlipayData } = weiUser.lib.utils.alipay;
const {
  ERROR
} = weiUser.common.error;
const {
  preUnifiedLogin,
  postUnifiedLogin
} = weiUser.lib.utils.unifiedLogin;
const {
  LOG_TYPE
} = weiUser.common.constants;
const {
  preBind,
  postBind
} = weiUser.lib.utils.relate;

/**
 * 支付宝手机登录
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#login-by-alipay
 * @param {Object} params
 * @param {String} params.encryptedData   支付宝小程序客户端登录返回的密文
 * @param {String} params.inviteCode  邀请码
 * @param {String} params.type  登录类型，不填：用户没有注册会自动注册，login：用户没有注册不能登录
 * @returns
 */
module.exports = async function (params = {}) {
  const schema = {
    encryptedData: 'string',
    inviteCode: {
      type: 'string',
      required: false
    }
  }
	this.middleware.validate(params, schema)
	
	const { encryptedData, inviteCode } = params
	
	const { code, mobile } = decryptAlipayData.call(this, { encryptedData });
	if (code !== '10000') {
		await this.middleware.uniIdLog({
		  success: false,
		  type: LOG_TYPE.LOGIN
		})
		throw {
		  errCode: ERROR.GET_THIRD_PARTY_ACCOUNT_FAILED
		}
	}
	
	const { type, user } = await preUnifiedLogin.call(this, {
	  user: {
	    mobile
	  },
		type: params.type
	})
	
	let extraData = {
	  mobile_confirmed: 1
	}
	if (type === 'login') {
	  // 绑定手机号
	  if (!user.mobile_confirmed) {
	    const bindAccount = {
	      mobile
	    }
	    await preBind.call(this, {
	      uid: user._id,
	      bindAccount,
	      logType: LOG_TYPE.BIND_MOBILE
	    })
	    await postBind.call(this, {
	      uid: user._id,
	      bindAccount,
	      extraData: {
	        mobile_confirmed: 1
	      },
	      logType: LOG_TYPE.BIND_MOBILE
	    })
	    extraData = {
	      ...extraData,
	      ...bindAccount
	    }
	  }
	}
  return postUnifiedLogin.call(this, {
    user,
    extraData: {
      ...extraData
    },
    isThirdParty: false,
    type,
    inviteCode
  })
}
